import Fields from "./Fields.tsx";
import TableTypes from "../../../model/TableTypes.ts";
import {TableData} from "../../../model/TableData.ts";
import {useRef, useState} from "react";
import {baseUrl} from "../../../settings/Settings.ts";
import * as bootstrap from "bootstrap";
import useModalState from "../../../settings/GlobalStates.ts";


const Modal = (props: { type: TableTypes, data?: TableData, updateDataOnPage: () => void }) => {

    const closeButtonRef = useRef(null)

    const state = useModalState((state) => state.isCalledFromFAB)

    const [selectedFile, setSelectedFile] = useState<any>(null);


    //Toast trigger on save
    const toastLiveExample = document.getElementById('liveToast');

    const triggerToast = () => {
        const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample);
        toastBootstrap.show();
    };

    const {type, data, updateDataOnPage} = props
    const [fields, setFields] = useState(data)


    switch (type) {
        case TableTypes.USERS:

            break
        case TableTypes.STACKS:

    }


    const updateBook = async () => {
        try {
            const data = {
                bookId: fields?.bookId.toString() || '',
                categoryId: fields?.categoryId,
                stackId: fields?.stackId.toString() || '',
                ownerId: fields?.ownerId.toString() || '',
                condition: fields?.condition || '',
                fee: fields?.fee.toString() || '',
                price: fields?.price.toString() || '',
                status: fields?.status.toString() || '',
            };

            console.log(data)

            const response = await fetch(`${baseUrl}/api/books/update`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            });

            console.log(response)

            if (response.ok) {
                updateDataOnPage();
                closeButtonRef.current?.click();
                triggerToast();


                // close modal window
            } else {
                console.error('Error updating book:', response.status);
            }
        } catch (error) {
            console.error('Error updating book:', error);
        }
    }


    const createBook = async () => {
        try {
            const data = {
                bookId: fields?.bookId || '',
                categoryId: fields?.categoryId,
                stackId: fields?.stackId || '',
                ownerId: fields?.ownerId || '',
                condition: fields?.condition || '',
                fee: fields?.fee || '',
                price: fields?.price || '',
                status: fields?.status || '',
            };

            const response = await fetch(`${baseUrl}/api/books/create`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            });

            if (response.ok) {
                updateDataOnPage();
                closeButtonRef.current?.click();
                triggerToast();

                // close modal window
            } else {
                console.error('Error creating book:', response.status);
            }
        } catch (error) {
            console.error('Error creating book:', error);
        }

    }


    const updateStack = async () => {
        try {
            const response = await fetch(`${baseUrl}/api/stack/${fields?.stackId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(fields),
            });


            if (response.ok) {
                const result = await response.json();

                updateDataOnPage();
                closeButtonRef.current?.click()
                triggerToast();


                //close modal window
            } else {
                console.error('Error updating stack:', response.status);
            }
        } catch (error) {
            console.error('Error updating stack:', error);
        }

    }

    const createStack = async () => {
        try {
            const data = {
                stackId: fields?.stackId || '',
                categoryId: fields?.categoryId,
                title: fields?.title || '',
                description: fields?.description || '',
                author: fields?.author || '',
            };

            // if (selectedFile) {
            //    data.file = selectedFile;
            //   }

            const response = await fetch(`${baseUrl}/api/stack/create`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            });

            if (response.ok) {

                updateDataOnPage();
                closeButtonRef.current?.click();
                triggerToast();

                // close modal window
            } else {
                console.error('Error updating stack:', response.status);
            }
        } catch (error) {
            console.error('Error updating stack:', error);
        }
    };


    const createData = () => {
        switch (type) {
            case TableTypes.STACKS:
                createStack()
                break

            case TableTypes.BOOKS:
                createBook()
                break
        }
    }


    const updateData = () => {

        switch (type) {
            case TableTypes.STACKS:
                updateStack()
                break
            case TableTypes.BOOKS:
                updateBook()
                break

        }
    }


    return (

        <div className={"modal fade"} id="exampleModal" aria-labelledby="exampleModalLabel"
             aria-hidden="true">
            <div className="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                <div className="modal-content">
                    <div className="modal-header">
                        <h1 className="modal-title fs-5" id="exampleModalLabel">{fields?.title || ''}</h1>
                        <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div className="modal-body">
                        <Fields setFields={setFields} setFile={setSelectedFile} type={type} data={data}/>

                    </div>

                    <div className="modal-footer">
                        <button type="button" className="btn btn-outline-secondary rounded-5 outlined-button "
                                data-bs-dismiss="modal" ref={closeButtonRef}>Close
                        </button>
                        {state &&
                            <button type="button" className="btn rounded-5 primary-button" onClick={createData}>
                                Create
                            </button> ||
                            <button type="button" className="btn rounded-5 primary-button" onClick={updateData}>Save
                                changes
                            </button>
                        }

                    </div>
                </div>
            </div>
        </div>
    )
}

export default Modal